import 'dart:core';

import 'package:dio/dio.dart';
import 'package:manager/exts/app_ext.dart';
import 'package:manager/res/string.dart';

class AppException implements Exception {
  final String msg;
  final dynamic code;

  AppException({required this.code, required this.msg});

  @override
  String toString() => '$code--$msg';

  String message() => msg;

  dynamic codes() => code;

  factory AppException.create(DioException dioError) {
    loggerMsg(dioError.message);
    cancelLoading();
    late AppException exception;
    switch (dioError.type) {
      case DioExceptionType.cancel:
        exception = AppException(code: -1, msg: StringPool.cancel_request);
        break;
      case DioExceptionType.sendTimeout:
        exception = AppException(code: -1, msg: StringPool.send_timeout);
        break;
      case DioExceptionType.receiveTimeout:
        exception = AppException(code: -1, msg: StringPool.read_timeout);
        break;
      case DioExceptionType.badResponse:
        try {
          switch (dioError.response!.statusCode) {
            case 400:
              exception = AppException(
                  code: dioError.response!.statusCode ?? -1,
                  msg: dioError.message??'未知错误');
              break;
            case 401:
              showToast('账号密码错误');
              break;
            case 424:
              exception = AppException(
                  code: dioError.response!.statusCode ?? -1,
                  msg: '登录已过期,请重新登录');
              showToast('登录已过期,请重新登录');
              logout();
              break;
            case 500:
              exception = AppException(
                  code: dioError.response!.statusCode ?? -1,
                  msg: dioError.message??'未知错误');
              showToast('服务器出错[500]');
              break;
            default:
              exception = AppException(
                  code: dioError.response!.statusCode ?? -1,
                  msg: dioError.message??'未知错误');
              break;
          }
        } on Exception catch (_) {
          exception = AppException(code: -1, msg: StringPool.unknow_error);
        }
        break;
      default:
        exception = AppException(code: -1, msg: dioError.message??'未知错误');
        break;
    }
    return exception;
  }
}
